package ws

import (
	"el/app/libs"
	"el/app/models"
	"encoding/json"
	"log"

	"github.com/gorilla/websocket"
	"github.com/labstack/echo/v4"
)

func NewAdminServer(c echo.Context) error {
	admin_id := uint64(libs.StringToInt(c.Param("admin_id")))

	admin := &models.AdminUsers{Id: admin_id}

	admin.InfoById()

	if admin.Id == 0 {
		return libs.Error(c, 1, "用户不存在")
	}

	conn, err := upgrader.Upgrade(c.Response().Writer, c.Request(), nil)
	if err != nil {
		return libs.Error(c, 1, "传输失败:"+err.Error())
	}

	var kefu Admin
	kefu.Id = admin.Username
	kefu.Name = admin.Name
	kefu.Conn = conn
	AddKefuToList(&kefu)

	for {
		//接受消息
		var receive []byte
		messageType, receive, err := conn.ReadMessage()
		if err != nil {
			SendPingToKefuClient(kefu.Id)
			return libs.Error(c, 1, "传输失败:"+err.Error())
		}

		message <- &Message{
			conn:        conn,
			content:     receive,
			context:     c,
			messageType: messageType,
		}
	}
}
//指定客服发送消息
func SendAdminMessage(username string, str []byte) {
	conns, ok := KefuList[username]
	if !ok {
		return
	}
	for _, kefu := range conns {
		kefu.Mux.Lock()
		defer kefu.Mux.Unlock()
		err := kefu.Conn.WriteMessage(websocket.TextMessage, str)
		if err != nil {
			log.Println("发送消息失败" + err.Error())
		}
	}
}
//添加客服到列表
func AddKefuToList(kefu *Admin) {
	var newKefuConns = []*Admin{kefu}
	KefuConns := KefuList[kefu.Id]

	for _, otherKefu := range KefuConns {
		msg := TypeMessage{
			Type: "many pong",
		}
		str, _ := json.Marshal(msg)
		err := otherKefu.Conn.WriteMessage(websocket.TextMessage, str)
		if err == nil {
			newKefuConns = append(newKefuConns, otherKefu)
		}
	}
	KefuList[kefu.Id] = newKefuConns
}

//测试客服是否在线
func SendPingToKefuClient(kefuId string) {
	msg := TypeMessage{
		Type: "many pong",
	}
	str, _ := json.Marshal(msg)

	kfConns := KefuList[kefuId]
	var newKefuConns = []*Admin{}
	for _, kefuConn := range kfConns {
		if kefuConn == nil {
			continue
		}
		kefuConn.Mux.Lock()
		defer kefuConn.Mux.Unlock()
		err := kefuConn.Conn.WriteMessage(websocket.TextMessage, str)
		if err == nil {
			newKefuConns = append(newKefuConns, kefuConn)
		}
	}

	if len(newKefuConns) > 0 {
		KefuList[kefuId] = newKefuConns
	} else {
		delete(KefuList, kefuId)
	}
}
